package com.base.system.managedBean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.SaveState;
import org.operamasks.faces.component.layout.impl.UIWindow;
import org.operamasks.faces.component.tree.base.TreeDataProvider;
import org.operamasks.faces.component.tree.base.TreeDataProviderAdapter;
import org.operamasks.faces.component.tree.impl.UITree;
import org.operamasks.faces.component.tree.impl.UITreeNode;
import org.operamasks.faces.user.util.Browser;

import com.base.commons.SpringBeanHolder;
import com.base.security.entity.Resource;
import com.base.security.service.SecurityEntityManager;

/**
 * 
 * This managed bean is generated automatically
 */
@ManagedBean(name = "system_editResourceRoleBean", scope = ManagedBeanScope.SESSION)
public class EditResourceRoleBean implements Serializable {
	private SecurityEntityManager seManager = SpringBeanHolder
			.getBean("securityEntityManager");
	// 过滤后的用户
	private List<SelectItem> filteredUsers;
	// 角色已经拥有的用户
	private List<SelectItem> roleUsers;
	// 搜索词
	private String prefix;
	// 传进来的角色Id
	@SaveState
	private String roleId;
	@Inject
	private FacesContext context;
	@Bind(id = "showSuccess", attribute = "binding")
	private UIWindow showSuccess_binding;
	@Bind
	private UITree resourceTree;

	@BeforeRender
	public void beforeRender(boolean isPostback) {
		if (!isPostback) {
			roleId = context.getExternalContext().getRequestParameterMap().get(
					"roleId");
		}
	}

	@Bind(id = "resourceTree")
	private TreeDataProvider resourceTreeProvider = new TreeDataProviderAdapter() {
		public Object[] getChildren(Object nodeData) {
			if (nodeData == null) {
				return new String[] { "已分配权限" };
			}
			if ("已分配权限".equals(nodeData.toString())) {
				List<String> list = seManager.getModule();
				list.add("其他模块");
				if (list != null)
					return list.toArray();
			}
			if (!"已分配权限".equals(nodeData.toString())) {
				if ("其他模块".equals(nodeData.toString())) {
					List<Resource> sub = seManager.getResourceByModuleNull();
					if (sub != null)
						return sub.toArray();
				} else {
					List<Resource> sub = seManager.getResourceByModule(nodeData
							.toString());
					if (sub != null)
						return sub.toArray();
				}
			}
			return null;
		}

		public String getHref(Object nodeData) {
			if (nodeData instanceof Resource) {
				String str = new String();
				Resource resource = (Resource) nodeData;
				return resource.getId().toString();
			} else {
				return null;
			}
		}

		public String getHrefTarget(Object nodeData) {
			return null;
		}

		public String getIcon(Object nodeData) {
			return null;
		}

		public String getText(Object nodeData) {
			if (nodeData instanceof Resource) {
				String str = new String();
				Resource resource = (Resource) nodeData;
				return resource.getDisplayName();
			}
			if (nodeData == null) {
				return "其他模块";
			}
			return nodeData.toString();
		}

		public boolean isCascade(Object nodeData) {
			return true;
		}

		public Boolean isChecked(Object nodeData) {
			if (nodeData instanceof Resource) {
				if (roleId != null && !"".equals(roleId)) {
					List<Resource> users = seManager
							.getResourcesByRoleId(Integer.parseInt(roleId));
					for (int i = 0; i < users.size(); i++) {
						if (nodeData.equals(users.get(i))) {
							return true;
						}
					}
				}
			}
			return false;
		}

		public boolean isExpanded(Object nodeData) {
			return true;// 原来为false，速度特别慢，改为true之后，速度马上提升
		}
	};

	@Action(id = "saveUserRole")
	public void saveUserRole() {
		List<UITreeNode> list = resourceTree.getCheckedNodes();
		String selectedUsers = null;
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getHref() != null) {
				if (selectedUsers != null) {
					selectedUsers = selectedUsers + "," + list.get(i).getHref();
				} else {
					selectedUsers = list.get(i).getHref();
				}
			}
		}
		if (selectedUsers == null) {
			selectedUsers = "";
		}
		seManager.mergeRoleResource(selectedUsers, roleId);
		roleUsers = this.getUsersOfRole();
		context.getExternalContext().getSessionMap().put("RESOURCEROLE",
				roleUsers);
		String script = "closeWindow('prvilidge_relation')";
		Browser.execClientScript("window.parent", script);
	}

	// 值改变后触发的事件
	public void prefixChanged(ValueChangeEvent event) {
		filteredUsers = buildFilteredUsers((String) event.getNewValue());
	}

	private List<SelectItem> buildFilteredUsers(String prefix) {
		// System.out.println("输入进来的值是：" + prefix);
		List<SelectItem> result = new ArrayList<SelectItem>();
		if (prefix != null)
			prefix = prefix.trim();
		List<Resource> users = new ArrayList<Resource>();
		if ("".equals(prefix))
			users = seManager.getAllResource();
		else
			users = seManager.getResourcesByDisplayName(prefix);
		// System.out.println("取到的user size:" + users.size());
		for (Resource su : users) {
			result.add(new SelectItem(su.getId(), su.getDisplayName()));
		}
		return result;
	}

	public List<SelectItem> getFilteredUsers() {
		if (filteredUsers == null)
			filteredUsers = getAllItems();
		return filteredUsers;
	}

	// 得到全部用户
	private List<SelectItem> getAllItems() {
		List<Resource> users = seManager.getAllResource();
		List<SelectItem> items = new ArrayList<SelectItem>();
		for (Resource su : users) {
			items.add(new SelectItem(su.getId(), su.getDisplayName()));
		}
		return items;
	}

	// 得到角色已经分配的用户
	private List<SelectItem> getUsersOfRole() {
		List<SelectItem> items = new ArrayList<SelectItem>();
		if (roleId != null && !"".equals(roleId)) {
			List<Resource> users = seManager.getResourcesByRoleId(Integer
					.parseInt(roleId));
			for (Resource su : users) {
				items.add(new SelectItem(su.getId(), su.getDisplayName()));
			}

		}
		return items;
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public void setFilteredUsers(List<SelectItem> filteredUsers) {
		this.filteredUsers = filteredUsers;
	}

	public List<SelectItem> getRoleUsers() {
		return roleUsers;
	}

	public void setRoleUsers(List<SelectItem> roleUsers) {
		this.roleUsers = roleUsers;
	}

}
